package domain;

/**
 * 封装HttpRequest请求
 */

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 *  @数据格式
 */
//    GET / HTTP/1.1
//    Host: 127.0.0.1:8080
//    Connection: keep-alive
//    Upgrade-Insecure-Requests: 1
//    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
//    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
//    Purpose: prefetch
//    Accept-Encoding: gzip, deflate, br
//    Accept-Language: zh-CN,zh;q=0.9,en;q=0.8

public class HttpRequest {

     private String method;     //请求方式  （GET or POST）
     private String requestURI; //资源路径
     private String vision;     //HTTP协议版本（普遍为1.1）
     private List<Header> headers; //请求头数据类集合
     private SelectionKey selectionKey; //传入选择器选中的通道（通道中包含有效信息）


    /**
     * 构造方法
     * @param selectionKey 必须以SelectionKey为参数构造HttpRequest对象
     */
    public HttpRequest(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }

    /**
     * GET and SET method
     */
    public String getMethod() {
        return method;
    }


    public void setMethod(String method) {
        this.method = method;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public void setRequestURI(String requestURI) {
        this.requestURI = requestURI;
    }

    public String getVision() {
        return vision;
    }

    public void setVision(String vision) {
        this.vision = vision;
    }

    public List<Header> getHeaders() {
        return headers;
    }

    public void setHeaders(List<Header> headers) {
        this.headers = headers;
    }

    public SelectionKey getSelectionKey() {
        return selectionKey;
    }

    public void setSelectionKey(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }


    /**
     * member method
     */

    public void parse() {
        SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            socketChannel.configureBlocking(false);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            int read = socketChannel.read(byteBuffer);

            while (read > 0){
                byteBuffer.flip();
                stringBuilder.append(new String(byteBuffer.array(),0,read));
                byteBuffer.clear();
                read = socketChannel.read(byteBuffer);
            }
            System.out.println("HttpRequestMessage --------------");
            System.out.println(stringBuilder);

            /**
             * @问题 浏览器会发送连接请求但没有Request信息
             * 导致程序发生空指针异常
             * @throws NullPointerException
             * 导致出现数组越界异常
             * @throws ArrayIndexOutOfBoundsException
             *
             * @解决
             * 判断是否存在Request请求数据，若数据不存在，则关闭通道
             */

            if(new String(stringBuilder).equals("")){
                socketChannel.close();
                return;
            }
            parseWithHttpRequest(stringBuilder);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void parseWithHttpRequest(StringBuilder stringBuilder) {

        String requestMsg = new String(stringBuilder);

        String[] splits = requestMsg.split("\r\n");

        //处理请求行
        String[] s = splits[0].split(" ");
        this.setMethod(s[0]);
        if(s[1] == null){
            System.out.println("hh");
        }
        this.setRequestURI(s[1]);
        this.setVision(s[2]);

        //处理请求头数据
        ArrayList<Header> headers = new ArrayList<>();
        for (int i = 1; i < splits.length; i++) {
            String[] split = splits[i].split(": ");
            headers.add(new Header(split[0],split[1]));
        }
        this.setHeaders(headers);


    }
}
